<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\LoginRequest;
use App\Models\Admin;
use App\Service\Jwt\TokenService;
use Carbon\Carbon;
use DB;
use Exception;
use Hash;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Date;

class AuthController extends AdminBaseController
{

    /**
     * 登录
     * @param LoginRequest $request
     * @param TokenService $tokenService
     * @return JsonResponse|object
     */
    public function login(LoginRequest $request, TokenService $tokenService) {
        $data = $request->validated();
        $admin = Admin::where('username', $data['username'])->first();
        if (!$admin) return $this->restful(null, false, '用户不存在');
        if (!Hash::check($data['password'], $admin->password)) return $this->restful(null, false, '密码不正确');

        if ($admin->status == 2) return $this->restful(null, false, '已被禁止登录');

        // 签发Token
        $token = $tokenService->createToken($admin);

        return $this->restful([
            'id' => $admin->id,
            'username' => $admin->username,
            'avatar' => $admin->avatar,
            'roles' => [$admin->role],
            'token_type' => 'Bearer',
            'expires' => Carbon::now()->addHours(120)->timestamp,
            'accessToken' => $token,
            'refreshToken' => $token
        ]);
    }

    /**
     * 刷新token
     * @param Request $request
     * @param TokenService $tokenService
     * @return JsonResponse|object
     */
    public function refreshToken(Request $request, TokenService $tokenService)
    {
        $params = $request->validate([
            'refreshToken' => 'bail|required|string'
        ]);

        try {
            $jti = json_decode(base64_decode(explode('.' , $params['refreshToken'])[1]), true)['jti'];

            $token = DB::table('oauth_access_tokens')->where('id', $jti)->first();
            $admin = Admin::find($token->user_id);
            $token = $tokenService->createToken($admin);

            return $this->restful([
                'token_type' => 'Bearer',
                'expires' => Date::make(now()->addSeconds(86400)->format('Y-m-d')),
                'accessToken' => $token,
                'refreshToken' => $token
            ]);
        }catch (Exception $e) {
            return $this->restful(null, false, '刷新失败');
        }
    }
}
